package edu.cmu.vlis.wassup.publisher;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;

import org.mybeans.factory.RollbackException;

import com.sun.messaging.Topic;

import edu.cmu.vlis.wassup.db.Announcement;
import edu.cmu.vlis.wassup.db.UnprocessedAnnouncement;
import edu.cmu.vlis.wassup.db.UnprocessedAnnouncementDao;
import edu.cmu.vlis.wassup.db.UnprocessedAnnouncement_Tag_Dao;

public class UserEventPoller extends AbstractPoller{

    UnprocessedAnnouncementDao upd = null;
    UnprocessedAnnouncement_Tag_Dao upt = null;

    public UserEventPoller(){
        super(20000);
    }

    public void initialize() throws Exception{
        this.upd = new UnprocessedAnnouncementDao();
        this.upt = new UnprocessedAnnouncement_Tag_Dao(); 

    }
    public  int getMessagesNputInPublisherQ() {
    	UnprocessedAnnouncement ann[]=null;
        if(this.upd == null || this.upt == null){
            try {
                initialize();
            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }
        }

        try {
            ann =  this.upd.getAll();
            for(UnprocessedAnnouncement a : ann) {
                ObjectMessage objMesg = this.topicSession.createObjectMessage(a);

                //find all the topic in it
                String[] topicList =this.upt.getTagFromAnnouncement(a);
                //Place in announcement Bean according to topic.
                for(String topic : topicList) {
                    this.topicPublisher.publish(new Topic(topic), objMesg);
                }
                this.upd.delete(a.getAnnouncement_id());
            }
        } catch (RollbackException e) {
            e.printStackTrace();
            return -1;
        }catch (JMSException e) {
            e.printStackTrace();
            return -1;
        }

        return ann.length;
    }

    public String getPollerName() {
        return "UserEventPoller";
    }

    @Override
    public int getID() {
        // TODO Auto-generated method stub
        return 20000;
    }

}
